#include "BlockQueue.hpp"
#include "Test.hpp"
#include <ctime>
#include <unistd.h>
using namespace std;

void *consumer(void* args) //消费者
{
    BlockQueue<Test>* bq = static_cast<BlockQueue<Test>*>(args);
    while(true)
    {
        usleep(1000);
        Test data;
        bq->pop(data); //购买商品
        data();
        cout<<pthread_self()<<" | 消费者:"<< data.calcu() << data.outcome() <<endl; //使用商品
    }
}

void *productor(void* args) //生产者
{
    BlockQueue<Test>* bq = static_cast<BlockQueue<Test>*>(args);
    string oper("+-*/%");
    while(true)
    {
        sleep(1); //生产速度降低
        //int data = rand()%10; //获取商品
        int x = rand()%1000+1;
        int y = rand()%1000+1;
        char op = oper[rand()%oper.size()];
        Test data(x,y,op);
        bq->push(data); //送达商品
        //cout<<pthread_self()<<" | 生产者: 一次生产完成!"<<endl;
        cout<<pthread_self()<<" | 生产者: "<<data.calcu()<<"?"<<endl;

    }
}

int main()
{
    srand(time(nullptr)^getpid()); //初始化随机数种子
    //BlockQueue<int>* bq = new BlockQueue<int>();
    BlockQueue<Test>* bq = new BlockQueue<Test>();

    pthread_t p[2],c[3];
    pthread_create(p,nullptr,productor,(void*)bq);
    pthread_create(p+1,nullptr,productor,(void*)bq);

    pthread_create(c,nullptr,consumer,(void*)bq);
    pthread_create(c+1,nullptr,consumer,(void*)bq);
    pthread_create(c+2,nullptr,consumer,(void*)bq);

    pthread_join(c[0],nullptr);
    pthread_join(c[1],nullptr);
    pthread_join(c[2],nullptr);

    pthread_join(p[0],nullptr);
    pthread_join(p[1],nullptr);

    delete bq;
    return 0;
}